<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/6/19
 * Time: 10:34
 */

namespace WenRuns\Laravel\Admin\Form\Field;


use Encore\Admin\Form\Field;
use WenRuns\Laravel\Admin\Form;

class Tabs extends Field
{
    protected $view = 'WenAdmin::form.tabs';

    protected $_tabs = [];

    protected $_clickEventFunc = '';

    protected $fieldName = '';

    protected $_max_height = '100%';

    protected $_max_width = '100%';

    protected $_min_height = '100%';

    protected $_min_width = '100%';


    public function __construct($column = '', array $arguments = [])
    {
        parent::__construct($column, $arguments);
    }

    public function getViewElementClasses(): array
    {
        if ($this->horizontal) {
            return [
                'label' => "col-sm-{$this->width['label']} {$this->getLabelClass()}",
                'field' => "col-sm-{$this->width['field']}",
                'form-group' => $this->getGroupClass(true),
            ];
        }
        return ['label' => $this->getLabelClass(), 'field' => '', 'form-group' => ''];
    }

    /**
     * @param array $arguments
     * @return string
     */
    public function formatLabel($arguments = []): string
    {
        if (isset($arguments[0]) && is_callable($arguments[0])) {
            $column = is_array($this->column) ? current($this->column) : $this->column;

            $this->_tabs[] = [
                'tabName' => $column,
                'closure' => $arguments[0],
            ];
            return ucfirst($column);
        } else {
            return parent::formatLabel($arguments); // TODO: Change the autogenerated stub
        }
    }

    public function setForm(\Encore\Admin\Form $form = null)
    {
        $this->form = $form;
        $this->makeTab();
        return $this;
    }

    /**
     * @param $fieldName
     * @return $this
     */
    public function setFieldName($fieldName)
    {
        $this->fieldName = $fieldName;
        return $this;
    }

    /**
     * @param $eventFun
     * @return $this
     */
    public function clickEvent($eventFun)
    {
        $this->_clickEventFunc = $eventFun;
        return $this;
    }

    /**
     * @param $title
     * @param \Closure $closure
     * @return $this
     */
    public function wenTab($title, \Closure $closure)
    {
        $this->_tabs[] = [
            'tabName' => $title,
            'closure' => $closure,
        ];
        $this->makeTab($title, $closure);
        return $this;
    }

    /**
     * 设置最大宽高
     * @param $width
     * @param $height
     * @return $this
     */
    public function max($width, $height)
    {
        $this->_max_height = $height;
        $this->_max_width = $width;
        return $this;
    }

    protected $subForms = [];

    protected function makeTab($column = null, \Closure $closure = null)
    {
        $width = $this->form->builder()->getWidth();
        if (empty($column) || empty($closure)) {
            foreach ($this->_tabs as $key => $item) {
                $form = new Form($this->form->model());
                $form->setWidth($width['field'] ?? 8, $width['label'] ?? 2);
                $closure = $item['closure'];
                call_user_func($closure, $form);
                $this->subForms[] = [
                    'form' => $form,
                    'tabName' => $item['tabName'],
                ];
            }
        } else {
            $form = new Form($this->form->model());
            $form->setWidth($width['field'] ?? 8, $width['label'] ?? 2);
            call_user_func($closure, $form);
            $this->subForms[] = [
                'form' => $form,
                'tabName' => $column,
            ];
        }
    }


    /**
     * 设置最新宽高
     * @param $width
     * @param $height
     * @return $this
     */
    public function min($width, $height)
    {
        $this->_min_height = $height;
        $this->_min_width = $width;
        return $this;
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|string
     */
    public function render()
    {
        $tabs = [];
        $activeTab = request('__wen_tabs_active_name');
        $activeClass = '';
        $id = $this->form->model()->getKey();
        foreach ($this->subForms as $k => $tab) {
            /** @var Form $form */
            $form = $tab['form'];
            $width = $form->builder()->getWidth();
            $form->setWidth($width['field'] ?? 8, $width['label'] ?? 2);
            if ($id) {
                $form->edit($id);
            }
            $content = $form->render();
            $reg = '/<form[^>]*>([\s\S]*)<div\s*class="box-footer"\s*>/';
            preg_match($reg, $content, $result);
            $tabClass = md5($tab['tabName'] . time() . mt_rand(0, 9999));
            $tabs[] = [
                'tabName' => $tab['tabName'],
                'content' => $result[1] ?? '',
                'class' => $tabClass,
            ];
            if ($activeTab == $tab['tabName'] || (empty($activeTab) && $k == 0)) {
                $activeTab = $tab['tabName'];
                $activeClass = $tabClass;
            }
        }
        if (empty($activeTab)) {
            $activeTab = $tabs[0]['tabName'] ?? '';
            $activeClass = $tabs[0]['class'] ?? '';
        }
        $this->addVariables([
            'tabs' => $tabs,
            'activeTab' => $activeTab,
            'activeClass' => $activeClass,
            'eventFunc' => $this->_clickEventFunc,
            'fieldName' => $this->fieldName,
            'maxHeight' => $this->_max_height,
            'maxWidth' => $this->_max_width,
            'minHeight' => $this->_min_height,
            'minWidth' => $this->_min_width,
        ]);
        $this->addScript();
        return parent::render(); // TODO: Change the autogenerated stub
    }

    protected function addScript()
    {
        $eventFn = $this->_clickEventFunc ? $this->_clickEventFunc : 0;
        $this->script = <<<SCRIPT
$(function(){
    $(".wen-tabs-name").click(function (e) {
        $(this).addClass('wen-tabs-name-active');
        $(this).siblings().removeClass('wen-tabs-name-active');
        $("." + e.currentTarget.dataset.class + "-tab-content").addClass('wen-tabs-show');
        $("." + e.currentTarget.dataset.class + "-tab-content").siblings().removeClass('wen-tabs-show');

        $("input[name='{$this->fieldName}']").val(e.currentTarget.dataset.name);
        var fn = {$eventFn};
        if(location.search){
            let query = location.search.substr(1).split("&");
            query.forEach((item, i)=>{
                if(item.indexOf("__wen_tabs_active_name")>=0){
                    query.splice(i, 1);
                }
            })
            history.pushState(null, null, '?__wen_tabs_active_name='+e.currentTarget.dataset.name+ "&"+query.join("&"));
        }else{
            history.pushState(null, null, '?__wen_tabs_active_name='+e.currentTarget.dataset.name);
        }
        if (fn) {
            fn.call(this, e)
        }
    });
});
SCRIPT;
    }

    public function column()
    {
        $columns = [];
        foreach ($this->subForms as $key => $item) {
            /** @var Form $form */
            $form = $item['form'];
            /** @var Field $field */
            foreach ($form->fields() as $field) {
                $disable = $field->attributes['disabled'] ?? false;
                if ($disable == 1) {
                    continue;
                }
                $column = $field->column();
                if (is_array($column)) {
                    $columns = array_merge($columns, $column);
                } else {
                    $columns[] = $column;
                }
            }
        }
        return $columns;
    }

}
